<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="19">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="status">
            <el-select
              clearable
              style="width: 200px"
              placeholder="请选择状态"
              @keyup.enter="handleQuery"
              v-model="queryParams.status"
            >
              <el-option
                v-for="dict in sys_news_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="5">
        <div class="flex justify-end flex-items-center">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </div>
      </el-col>

      <!--      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />-->
    </el-row>

    <el-table
      height="calc(100vh - 220px)"
      v-loading="loading"
      :data="swipeList"
      @selection-change="handleSelectionChange"
    >
      <template #empty>
        <EmptyRender class="m-20px" />
      </template>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="sort" width="100" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="图片" align="center" prop="imagePath" width="180">
        <template #default="scope">
          <el-image
            :src="uploadImgUrl + scope.row.imagePath || defaultImg"
            fit="cover"
            style="width: 120px; height: 80px; background-color: #f5f7fa"
          >
            <template #error>
              <div class="image-slot">
                <el-icon :size="30"><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.status === 0"
            :active-value="true"
            :inactive-value="false"
            @click.prevent="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建者" align="center" prop="createName" width="100" /> -->

      <el-table-column
        label="操作"
        width="140"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form
        hide-required-asterisk
        ref="swipeRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片:" prop="imagePath">
              <image-upload
                v-model="form.imagePath"
                :limit="1"
                :isShowTip="false"
                :isShowSizeTip="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标题:" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_notice_status" :key="dict.value" :value="dict.value">{{
                  dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="排序:" prop="sort">
              <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联内容:" prop="linkType">
              <el-select v-model="form.linkType" placeholder="请选择关联类型">
                <el-option label="无关联" value="0" />
                <el-option label="关联文章" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.linkType === '1'">
            <el-form-item label="" prop="relateUrl">
              <el-input v-model="form.relateUrl" placeholder="请输入文章链接" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Swipe">
  import {
    listNotice,
    getNotice,
    delNotice,
    addNotice,
    updateNotice,
    getNoticeSort,
    updateNoticeStatus,
    getNoticeSortMax,
  } from '@/api/system/img';
  import { Picture } from '@element-plus/icons-vue';

  const { proxy } = getCurrentInstance();
  const { sys_news_status, sys_notice_type } = proxy.useDict('sys_news_status', 'sys_notice_type');
  const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API);
  const swipeList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');

  // 添加默认图片
  const defaultImg = ref('/default-image.png'); // 替换为您的默认图片路径

  /** 自定义文章链接验证 */
  const validateLinkUrl = (rule, value, callback) => {
    if (form.value.linkType === '1' && !value) {
      callback(new Error('请输入文章链接'));
    } else {
      callback();
    }
  };

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      title: undefined,
      createBy: undefined,
      status: undefined,
    },
    rules: {
      imagePath: [{ required: true, message: '请上传图片', trigger: 'blur' }],
      title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
      sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
      // status: [{ required: true, message: '请选择', trigger: 'blur' }],
      linkType: [{ required: true, message: '请选择关联类型', trigger: 'change' }],
      relateUrl: [
        { required: true, message: '请输入文章链接', trigger: 'blur', validator: validateLinkUrl },
      ],
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询轮播图列表 */
  function getList() {
    loading.value = true;
    listNotice(queryParams.value).then((response) => {
      swipeList.value = response.rows;
      console.log('轮播图数据:', swipeList.value);
      // 打印第一条数据的结构
      if (swipeList.value && swipeList.value.length > 0) {
        console.log('第一条数据结构:', JSON.stringify(swipeList.value[0]));
      }
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }

  /** 表单重置 */
  function reset() {
    form.value = {
      status: '0',
      imagePath: undefined,
      title: undefined,
      sort: undefined,
      linkType: '0',
      relateUrl: undefined,
    };
    proxy.resetForm('swipeRef');
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm('queryRef');
    handleQuery();
  }

  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  async function handleAdd() {
    reset();
    open.value = true;
    title.value = '新增';
    const { nextSort } = await getNoticeSortMax();
    // form.sort
    form.value.sort = nextSort || 0;
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    getNotice(row.id).then((response) => {
      form.value = response.data;
      form.value.status = String(form.value.status);
      form.value.linkType = form.value.relateUrl ? '1' : '0';
      open.value = true;
      title.value = '编辑';
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs['swipeRef'].validate((valid) => {
      if (valid) {
        if (form.value.id != undefined) {
          updateNotice(form.value).then((response) => {
            proxy.$modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addNotice(form.value).then((response) => {
            proxy.$modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const swipeId = row.id;
    proxy.$modal
      .confirm('确定删除该图片？')
      .then(function () {
        return delNotice(swipeId);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  /** 修改状态操作 */
  function handleStatusChange(row) {
    const newStatus = row.status;
    const text = newStatus === 1 ? '启用' : '禁用';

    proxy.$modal
      .confirm('确定' + text + '该图片？')
      .then(function () {
        return updateNoticeStatus(row.id, row.status === 1 ? 0 : 1);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess(text + '成功');
      })
      .catch(() => {
        // 不做任何操作
      });
  }

  onMounted(() => {
    console.log('组件挂载完成，开始获取数据');
    getList();
  });
</script>

<style scoped>
  .image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: #f5f7fa;
    color: #909399;
    font-size: 30px;
  }

  .el-image {
    overflow: hidden;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
</style>
